package com.luban.authserver.config.customfilter;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class VerifyCodeFilter extends GenericFilterBean {

    private String defaultFilterProcessUrl = "/oauth/token";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (needVerifyCode()) {
            if ("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) {
                // 验证码验证
                String requestCaptcha = request.getParameter("code");
                String genCaptcha = (String) request.getSession().getAttribute("index_code");
                if (StringUtils.isEmpty(requestCaptcha))
                    throw new RuntimeException("验证码不能为空!");
                if (!genCaptcha.toLowerCase().equals(requestCaptcha.toLowerCase())) {
                    throw new RuntimeException("验证码错误!");
                }
            }
        }


        filterChain.doFilter(request, response);
    }

    /**
     * 是否开启验证码
     *
     * @return
     */
    private boolean needVerifyCode() {
        return false;
    }
}
